<?php
namespace App\Service\Admin;

class ShequService extends BaseService
{
    //社区

    //列表
    public static function index($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbShequ)->where('del', 0);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return self::toback(0, '', [], $total);
        }
        foreach ($res as &$v) {
            $areaOne = self::dbConn(self::$dbArea)->where('id', $v->area_id)->first();
            $area_name = $areaOne ? $areaOne->title : '';
            $city_id = $areaOne ? $areaOne->pid : 0;
            $cityOne = self::dbConn(self::$dbArea)->where('id', $city_id)->first();
            $city_name = $cityOne ? $cityOne->title : '';
            $pro_id = $cityOne ? $cityOne->pid : 0;
            $proOne = self::dbConn(self::$dbArea)->where('id', $pro_id)->first();
            $pro_name = $proOne ? $proOne->title : '';
            $v->pro_id = $pro_id;
            $v->city_id = $city_id;
            $v->areastr = $pro_name . '，' . $city_name . '，' . $area_name;
        }
        return self::toback(0, '', $res, $total);
    }

    //获取省市区
    public static function areaListByPid($pid = 0)
    {
        $ary[] = ['id' => 0, 'title' => '选择'];
        $res = self::dbConn(self::$dbArea)
            ->select('id', 'title')
            ->where('pid', $pid)
            ->get();
        if (!count($res)) {
            return self::toback(0, '', []);
        }
        foreach ($res as $v) {
            $ary[] = [
                'id' => $v->id, 'title' => $v->title,
            ];
        }
        return self::toback(0, '', $ary);
    }

    //添加
    public static function add($pas)
    {
        $pas['uptime'] = $pas['addtime'] = toDate();
        self::dbConn(self::$dbShequ)->insertGetId($pas);
        return self::toback();
    }

    //修改
    public static function modify($id, $pas)
    {
        $pas['uptime'] = toDate();
        self::dbConn(self::$dbShequ)->where('id', $id)->update($pas);
        return self::toback();
    }

    /**
     * 删除
     * @param id $id 场景ID
     * return array
     */
    public static function del($id)
    {
        self::dbConn(self::$dbShequ)
            ->where('id', $id)
            ->update(['del' => 1]);
        return self::toback();
    }
}